package cn.com.czpb.client.module.personal.acticity;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import cn.com.czpb.client.R;
import cn.com.czpb.client.app.App;
import cn.com.czpb.client.app.ToolBarActivityWhite;
import cn.com.czpb.client.custorm.CircleImageView;
import cn.com.czpb.client.model.event.ChangeLocationEvent;
import cn.com.czpb.client.model.event.ChangeNameEvent;
import cn.com.czpb.client.model.usercenter.UserEntity;
import cn.com.czpb.client.module.personal.WodeFragment;
import cn.com.czpb.client.module.personal.dialog.ChangeLocationDialog;
import cn.com.czpb.client.module.personal.dialog.ChangeNameOrSignDialog;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.CipherUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;
import cn.com.czpb.client.utils.TextUtils;


import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;
import com.yanzhenjie.durban.Controller;
import com.yanzhenjie.durban.Durban;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class AccountSetActivity extends ToolBarActivityWhite {
    @BindView(R.id.title_toolbar)
    TextView tv_title;
    @BindView(R.id.iv_user_account_activity)
    CircleImageView iv_user_account_activity;
    @BindView(R.id.tv_nickname_account_activity)
    TextView tv_nickname_account_activity;
    @BindView(R.id.tv_introduce_activity_account)
    TextView tv_introduce_activity_account;
    @BindView(R.id.tv_brith_account_activity)
    TextView tv_brith_account_activity;

    @BindView(R.id.tv_sex_account_activity)
    TextView tv_sex_account_activity;
    @BindView(R.id.tv_locate_account_activity)
    TextView tv_locate_account_activity;

    private static final int IMAGE_REQUEST_CODE = 450;
    private static final int CAMERA_REQUEST_CODE = 451;
    private static final int RESULT_REQUEST_CODE = 452;
    private String[] items = new String[]{"选择本地图片", "拍照"};
    private File imgFile;
    private final String IMAGE_FILE_NAME = "faceImage.jpg";
    private String[] items_sex = new String[]{"男", "女"};
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    init();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv_title.setText("账户设置");
        init();
        imgFile = getImgPath();
    }

    private void init() {
        if (spu.getUser() != null) {

            Glide.with(activity).load(spu.getUser().getAvatar_path()).crossFade().into(iv_user_account_activity);
            LogUtils.e("bitmap_--" + spu.getUser().getAvatar_path());
            tv_nickname_account_activity.setText(TextUtils.getLengthText(spu.getUser().getNickname(), 8));
            tv_introduce_activity_account.setText(TextUtils.getLengthText(spu.getUser().getDesc(), 8));
        }
        if (spu.getUser().getBirthday() != null) {
            tv_brith_account_activity.setText(spu.getUser().getBirthday());
        }
        if (spu.getUser().getSex() != null) {
            if ("1".equals(spu.getUser().getSex())) {
                tv_sex_account_activity.setText("男");
            } else if ("2".equals(spu.getUser().getSex())) {
                tv_sex_account_activity.setText("女");
            }
        }
        if (spu.getUser().getRegion() != null) {
            tv_locate_account_activity.setText(spu.getUser().getRegion());
        }

    }


    @Override
    public int setMyContentView() {
        return R.layout.activity_account_set;
    }

    @OnClick({
            R.id.introduce_activity_account_set,
            R.id.phonto_activity_account_set,
            R.id.nickname_activity_account_set,
            R.id.sex_activity_account_set,
            R.id.brith_activity_account_set,
            R.id.locate_activity_account_set
    })
    public void Click(View view) {
        switch (view.getId()) {
            case R.id.phonto_activity_account_set:
                changePhoto();
                break;
            case R.id.nickname_activity_account_set:
                ChangeNameOrSignDialog changeNameDialog = new ChangeNameOrSignDialog(
                        activity, R.style.ChangeNamedialog, 0); // 0为修改昵称 1为修改个人签名
                changeNameDialog.show();

                break;
            case R.id.introduce_activity_account_set:
                ChangeNameOrSignDialog changeNameDialog_1 = new ChangeNameOrSignDialog(
                        activity, R.style.ChangeNamedialog, 1); // 0为修改昵称 1为修改个人签名
                changeNameDialog_1.show();
                break;
            case R.id.sex_activity_account_set:
                changeSex();
                break;
            case R.id.brith_activity_account_set:
                DateShowDialog();
                break;
            case R.id.locate_activity_account_set:
                ChangeLocationDialog changeLocationDialog = new ChangeLocationDialog(activity, R.style.location_style);
                changeLocationDialog.show();
                break;
        }
    }

    private void changeSex() {

        new AlertDialog.Builder(activity).
                setTitle("修改昵称")
                .setItems(items_sex, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (i) {
                            case 0:
                                ChangeType("sex", "1");

                                break;
                            case 1:
                                ChangeType("sex", "2");

                                break;
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                disMissDialog();
            }
        }).setCancelable(true).show();
    }

    public void DateShowDialog() {
        final Calendar c = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {

                String brithday = i + "-" + (i1 + 1) + "-" + i2;
                if (i > c.get(Calendar.YEAR)) {
                    TUtils.toast("请选择正确的日期");
                    return;
                }
                if (i1 > c.get(Calendar.MONTH)) {
                    TUtils.toast("请选择正确的日期");
                    return;
                }
                if (i2 > c.get(Calendar.DAY_OF_MONTH)) {
                    TUtils.toast("请选择正确的日期");
                    return;

                }
                ChangeType("birthday", brithday);
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.setCancelable(true);
        datePickerDialog.show();
    }

    private void ChangeType(String type, String value) {
//
        Map<String, String> map = new HashMap<>();
        map.put(type, value);
        map.put("uid", spu.getUser().getUid());
        LogUtils.e("uid" + spu.getUser().getUid());
        Factory.provideHttpService().changeUser(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<UserEntity, Boolean>() {
                    @Override
                    public Boolean call(UserEntity userEntity) {
                        LogUtils.e("photo", userEntity.code);
//                        if ("200".equals(userEntity.code)) {
//
//                            return true;
//                        } else {
//                            TUtils.toast(userEntity.msg);
//                            return true;
//                        }
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {
                        if ("200".equals(userEntity.code)) {
                            TUtils.toast("修改成功");
                            spu.setUser(userEntity.data);
                            LogUtils.e("birth" + spu.getUser().getBirthday());
                            Message msg = handler.obtainMessage();
                            msg.what = 200;
                            handler.sendMessage(msg);
                        } else {
                            TUtils.toast(userEntity.msg);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.e("throwable------" + throwable.getMessage());
                    }
                });
    }


    @Subscribe
    public void onEventMainThread(ChangeNameEvent event) {
        LogUtils.i("登录成功");

        boolean nameChange = event.isNameChange();

        tv_nickname_account_activity.setText(TextUtils.getLengthText(spu.getUser().getNickname(), 8));
        tv_introduce_activity_account.setText(TextUtils.getLengthText(spu.getUser().getDesc(), 8));
        if (spu.getWifi().equals("1")) {

        }

    }

    @Subscribe
    public void onEventMainThread(ChangeLocationEvent event) {
        LogUtils.i("登录成功");

        boolean nameChange = event.islocationChange();

        tv_locate_account_activity.setText(spu.getUser().getRegion());

    }


    public void changePhoto() {
        new AlertDialog.Builder(activity)
                .setTitle("设置头像")
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0: {
//                                Intent intentFromGallery = new Intent();
//                                intentFromGallery.setType("image/*"); // 设置文件类型
//                                intentFromGallery
//                                        .setAction(Intent.ACTION_GET_CONTENT);
//                                activity.startActivityForResult(intentFromGallery,
//                                        IMAGE_REQUEST_CODE);
//                                Album.image(activity) // Image selection.
//                                        .multipleChoice()
//                                        .requestCode(200)
//                                        .columnCount(1)
//                                        .selectCount(1)
//                                        .camera(true)
//                                        .listener(new AlbumListener<ArrayList<AlbumFile>>() {
//                                            @Override
//                                            public void onAlbumResult(int requestCode, @NonNull ArrayList<AlbumFile> result) {
//
////                                                File cacheFile = App.getFile(result.get(0).getPath());
////                                                Uri uri = Uri.fromFile(cacheFile);
//                                                startPhotoZoom(result.get(0).getPath());
//                                            }
//
//                                            @Override
//                                            public void onAlbumCancel(int requestCode) {
//                                                TUtils.toast("取消");
//                                            }
//                                        })
//                                        .start();
                                Widget widget=Widget.newLightBuilder(activity)
                                        .title("选择图片")
                                        .statusBarColor(Color.WHITE) // 状态栏颜色。
                                        .toolBarColor(Color.WHITE) // Toolbar颜色。
                                        .navigationBarColor(Color.WHITE) // Android5.0+的虚拟导航栏颜色。
                                        .mediaItemCheckSelector(Color.BLUE, Color.GREEN) // 图片或者视频选择框的选择器。
                                        .bucketItemCheckSelector(Color.RED, Color.YELLOW) // 切换文件夹时文件夹选择框的选择器。
                                        .buttonStyle( // 用来配置当没有发现图片/视频时的拍照按钮和录视频按钮的风格。
                                                Widget.ButtonStyle.newLightBuilder(activity) // 同Widget的Builder模式。
                                                        .setButtonSelector(Color.WHITE, Color.WHITE) // 按钮的选择器。
                                                        .build()
                                        )
                                        .build();
                                Album.image(activity)
                                        .multipleChoice()
                                        .widget(widget)// Image selection.
                                        .requestCode(200)
                                        .camera(true)
                                        .columnCount(1)
                                        .selectCount(1)
                                        .onResult(new Action<ArrayList<AlbumFile>>() {
                                            @Override
                                            public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                                                startPhotoZoom(result.get(0).getPath());
                                            }
                                        })
                                        .onCancel(new Action<String>() {
                                            @Override
                                            public void onAction(int requestCode, @NonNull String result) {
                                            }
                                        })
                                        .start();
                            }
                            break;
                            case 1: {
//                                Intent intentFromCapture = new Intent(
//                                        MediaStore.ACTION_IMAGE_CAPTURE);
//                                intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT,
//                                        Uri.fromFile(imgFile));
//                                activity.startActivityForResult(intentFromCapture,
//                                        CAMERA_REQUEST_CODE);
//                                Album.camera(activity).
//                                        image()
//                                        .requestCode(CAMERA_REQUEST_CODE).listener(new AlbumListener<String>() {
//                                    @Override
//                                    public void onAlbumResult(int requestCode, @NonNull String result) {
//                                        LogUtils.e("string--" + result);
////                                        File cacheFile = App.getFile(result);
////                                        Uri uri = Uri.fromFile(cacheFile);
//                                        startPhotoZoom(result);
////                                        Glide.with(activity).load(result).crossFade().into(iv_user_account_activity);
////                                        Bitmap bitmap= BitmapFactory.decodeFile(result);
////
////                                        uploadPhoto(bitmap);
//                                    }
//
//                                    @Override
//                                    public void onAlbumCancel(int requestCode) {
//                                        TUtils.toast("取消");
//                                    }
//                                }).start();
                                Album.camera(activity) // 相机功能。
                                        .image() // 拍照。
                                        .requestCode(CAMERA_REQUEST_CODE)
                                        .onResult(new Action<String>() {
                                            @Override
                                            public void onAction(int requestCode, @NonNull String result) {
                                                LogUtils.e("string--" + result);
//                                        File cacheFile = App.getFile(result);
//                                        Uri uri = Uri.fromFile(cacheFile);
                                                startPhotoZoom(result);
//                                        Glide.with(activity).load(result).crossFade().into(iv_user_account_activity);
//                                        Bitmap bitmap= BitmapFactory.decodeFile(result);
//
//                                        uploadPhoto(bitmap);
                                            }
                                        })
                                        .onCancel(new Action<String>() {
                                            @Override
                                            public void onAction(int requestCode, @NonNull String result) {
                                                TUtils.toast("取消");
                                            }
                                        })
                                        .start();
                            }
                            break;
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }


    public File getImgPath() {
        File cacheFileDir;
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cacheFileDir = Environment.getExternalStorageDirectory();
        } else {
            cacheFileDir = activity.getApplicationContext().getCacheDir();
        }
        if (null != cacheFileDir && !cacheFileDir.exists()) {
            cacheFileDir.mkdirs();
        }
        File cacheFile = App.getFile(cacheFileDir.getAbsolutePath()
                + File.separator + "cyol" + File.separator + IMAGE_FILE_NAME);

        return cacheFile;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.i("requestCode-->" + requestCode + "  resultCode-->"
                + resultCode);
        switch (requestCode) {
            case IMAGE_REQUEST_CODE: {
                if (null != data) {
                    startPhotoZoom(data.getData());
                }
            }
            break;
            case CAMERA_REQUEST_CODE: {
                startPhotoZoom();
            }
            break;
            case RESULT_REQUEST_CODE: {
                if (data != null) {
//                    Bundle extras = data.getExtras();
//                    if (extras != null) {
//                        Bitmap photo = extras.getParcelable("data");
//                        uploadPhoto(photo);
//                        LogUtils.i("setphoto");
//                    } else {
//                        LogUtils.i("extras null");
//                    }
                    ArrayList<String> mImageList = Durban.parseResult(data);
                    Bitmap bitmap = BitmapFactory.decodeFile(mImageList.get(0));
                    uploadPhoto(bitmap);
                }
            }
            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private void uploadPhoto(Bitmap photo) {
        try {
            photo.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(
                    imgFile));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>();
        map.put("avatar", CipherUtils.base64Encode(photo));
        LogUtils.e("avatar---" + CipherUtils.base64Encode(photo));
        map.put("uid", spu.getUser().getUid());
        Factory.provideHttpService()
                .changeUser_PHOTO(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<UserEntity, Boolean>() {
                    @Override
                    public Boolean call(UserEntity userEntity) {
                        LogUtils.e("photo", userEntity.code);
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {
//                        TUtils.toast(userEntity.msg);
                        if ("200".equals(userEntity.code)) {
                            TUtils.toast("修改成功");
                            spu.setUser(userEntity.data);
                            Glide.with(activity).load(spu.getUser().getAvatar_path()).crossFade().into(iv_user_account_activity);
                            Intent intent = new Intent();
                            intent.setAction(WodeFragment.ACTION_USER);
                            activity.sendBroadcast(intent);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }

    public void startPhotoZoom() {
        Uri uri = Uri.fromFile(imgFile);
        startPhotoZoom(uri);
    }

    public void startPhotoZoom(String imagePathList) {
        Durban.with(this)
                // Che title of the UI.
                .title("图片裁剪")
                .statusBarColor(ContextCompat.getColor(this, R.color.color_df3031))
                .toolBarColor(ContextCompat.getColor(this, R.color.color_df3031))
                .navigationBarColor(ContextCompat.getColor(this, R.color.color_df3031))
                // Image path list/array.
                .inputImagePaths(imagePathList)
                // Image output directory.
                // Image size limit.
                .maxWidthHeight(200, 200)
                // Aspect ratio.
                .aspectRatio(1, 1)
                // Output format: JPEG, PNG.
                .compressFormat(Durban.COMPRESS_JPEG)
                // Compress quality, see Bitmap#compress(Bitmap.CompressFormat, int, OutputStream)
                .compressQuality(90)
                // Gesture: ROTATE, SCALE, ALL, NONE.
                .gesture(Durban.GESTURE_ALL)
                .controller(
                        Controller.newBuilder() // Create Builder of Controller.
                                .enable(false) // Enable the control panel.
                                .rotation(true) // Rotation button.
                                .rotationTitle(true) // Rotation button title.
                                .scale(true) // Scale button.
                                .scaleTitle(true) // Scale button title.
                                .build()) // Create Controller Config.
                .requestCode(RESULT_REQUEST_CODE)
                .start();
    }

    // 图片裁剪
    public void startPhotoZoom(Uri uri) {
        if (null == uri) {
            return;
        }
        //////
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        intent.putExtra("return-data", true);
        activity.startActivityForResult(intent, RESULT_REQUEST_CODE);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
